require './biginteger.js'

class node_stdout extends lisp_channel
  write: (data) ->
    process.stdout.write data

class node_stderr extends lisp_channel
  write: (data) ->
    process.stderr.write data

ballanced = (input) ->
  tokens = []
  chan = new lisp_channel input
  loop
    t = chan.readtoken()
    if t isnt EOFC
      tokens.push t
    else
      break

  parens = 0
  for tok in tokens
    switch tok
      when '('
        parens++
      when ')'
        parens--

  return parens is 0

lisp = new interpreter new lisp_channel(), new node_stdout(), new node_stderr()
lisp.initialize()
buf = ''
input_num = 1
process.stdout.write "substandard lisp on #{process.platform}\n[#{input_num++}]> "

process.stdin.resume()

process.stdin.on 'data', (chunk) ->
  buf += chunk
  if ballanced buf
    lisp.evaluate(buf)
    buf = ''
    process.stdout.write "\n[#{input_num++}]> "
  else
    process.stdout.write '... '
